package configs

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

var UpdaloadPath = ""
var UploadPathKey = string(os.PathSeparator) + "files"
var Port = "8080"
var HttpsPort = "8000"

func ReadServerConfigs() (configs map[string]string, staticdirs map[string]string) {
	staticdirs = make(map[string]string)
	configs = make(map[string]string)

	configs["port"] = Port
	configs["httpsPort"] = HttpsPort
	configs["host"] = "0.0.0.0"
	configs["env"] = "debug"

	exPath, _ := os.Getwd()
	filePath := exPath + string(os.PathSeparator) + "appConf.txt"
	file, err := os.OpenFile(filePath, os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("文件打开失败", err)
	}
	//及时关闭file句柄
	defer file.Close()
	//读原来文件的内容，并且显示在终端
	reader := bufio.NewReader(file)
	for {
		str, err := reader.ReadString('\n')

		if strings.HasPrefix(str, "#") { //以#开头的行默认为注释
			continue
		}

		//读取静态路径
		if strings.HasPrefix(str, "staticdirs") {
			dirInfos := strings.Split(strings.Trim(strings.Split(str, "=")[1], " "), " ")

			for _, item := range dirInfos {
				staticInfos := strings.Split(item, "-") //兼容windows文件系统不实用冒号分割而使用-分割，否则会被windows的盘符冒号影响
				if strings.HasSuffix(staticInfos[1], "\n") {
					staticInfos[1] = strings.Trim(staticInfos[1], "\n")
				}

				//设置静态路径
				if staticInfos[0] == UploadPathKey {
					UpdaloadPath = staticInfos[1]
					// fmt.Println("upDir is " + staticInfos[1])
				}

				staticdirs[staticInfos[0]] = staticInfos[1]
			}
		} else if strings.Contains(str, "=") {
			//读取其他配置，env、host、port等
			items := strings.Split(str, "=")
			configs[strings.Trim(strings.Trim(items[0], " "), "\n")] = strings.Trim(strings.Trim(items[1], " "), "\n")
			fmt.Print(items[0] + ":" + items[1])

		}

		if err == io.EOF {
			break
		}
	}

	fmt.Printf("port is :" + configs["port"])

	Port = configs["port"]

	fmt.Printf("Port is :" + Port)

	HttpsPort = configs["httpsPort"]

	value, ok := configs["port"]
	if ok {
		Port = value
	}
	return
}

func GetDbConfigs() (dbConfigs map[string]string) {
	dbConfigs = make(map[string]string)

	exPath, _ := os.Getwd()
	fmt.Printf("exPath is :" + exPath + "\n")
	filePath := exPath + "/dbConf.txt"
	file, err := os.OpenFile(filePath, os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("文件打开失败", err)
	}
	//及时关闭file句柄
	defer file.Close()
	//读原来文件的内容，并且显示在终端
	reader := bufio.NewReader(file)
	for {
		str, err := reader.ReadString('\n')
		if err != nil {
			break
		}
		if strings.HasPrefix(str, "#") || !strings.Contains(str, "=") {
			continue
		}
		// fmt.Println("str is :" + str)
		var strs = strings.Split(str, "=")
		dbConfigs[strings.Trim(strs[0], " ")] = strings.Trim(strings.Trim(strs[1], " "), "\n")
		// fmt.Println(strs[0] + " : " + strs[1])
	}
	return
}
